const router = require('koa-router')();
const scripts = require('./scripts/menu');

router.prefix('/api/menu', '菜单管理接口');

router.get('/all', async (ctx) => {
  let res = await ctx.sqlite.queryForList(scripts.getMenus);

  ctx.body = res;
}, '获取所有菜单信息');

router.post('/save', async (ctx) => {
  let info = ctx.request.body || {};

  if (!info.name) {
    ctx.body = ctx.getResponse('名称不能为空！');

    return;
  }

  let res = await ctx.sqlite.queryForObject(scripts.getMenu, { id: info.id || 0 });

  if (res.data) {
    await ctx.sqlite.execute(scripts.updateMenu, info);
  } else {
    await ctx.sqlite.execute(scripts.addMenu, info);
  }

  ctx.body = ctx.getResponse();
}, {
  desc: '保存菜单信息', body: {
    id: { type: 'integer', desc: '编号' },
    name: { type: 'string', desc: '名称' },
    url: { type: 'string', desc: '地址' },
    parentId: { type: 'integer', desc: '父节点' },
    icon: { type: 'string', desc: '图标' },
    operators: { type: 'string', desc: '操作点' },
    visible: { type: 'boolean', desc: '是否可见' },
    sortValue: { type: 'integer', desc: '排序值' }
  }
});

router.get('/user/:id/rights', async (ctx) => {
  let userId = ctx.params.id;

  ctx.body = await ctx.sqlite.queryForList(scripts.getUserRights, { userId });
}, { desc: '获取用户菜单权限', userId: '用户编号' });

router.post('/user/:id/rights', async (ctx) => {
  let userId = ctx.params.id;
  let rights = ctx.request.body || [];

  await ctx.sqlite.execute(scripts.removeUserRights, { userId });
  await ctx.sqlite.execute(scripts.addUserRight, rights);

  ctx.body = ctx.getResponse();
}, { desc: '设置用户权限', id: '用户编号' });

router.get('/role/:id/rights', async (ctx) => {
  let roleId = ctx.params.id;

  ctx.body = await ctx.sqlite.queryForList(scripts.getRoleRights, { roleId });
}, { desc: '获取角色菜单权限', roleId: '角色编号' });


router.post('/role/:id/rights', async (ctx) => {
  let roleId = ctx.params.id;
  let rights = ctx.request.body || [];

  await ctx.sqlite.execute(scripts.removeRoleRights, { roleId });
  await ctx.sqlite.execute(scripts.addRoleRight, rights);

  ctx.body = ctx.getResponse();
}, { desc: '设置角色权限', id: '角色编号' });

router.get('/rights/:userId', async (ctx) => {
  let userId = ctx.params.userId;

  ctx.body = await ctx.sqlite.queryForList(scripts.getUserFullRights, { userId });
}, { desc: '获取用户完整的权限', userId: '用户编号' });

module.exports = router;